#!/bin/bash

echo "开始部署研究生奖学金管理系统..."

# 1. 更新系统
echo "更新系统包..."
sudo apt update && sudo apt upgrade -y

# 2. 安装必要软件
echo "安装必要软件..."
sudo apt install -y openjdk-17-jdk mysql-server nginx git

# 3. 配置MySQL
echo "配置MySQL..."
sudo mysql_secure_installation

# 4. 创建数据库
echo "创建数据库..."
sudo mysql -u root -p < database_setup.sql

# 5. 构建后端
echo "构建后端应用..."
cd ../BeckendCode/GSS
./mvnw clean package -DskipTests
sudo mkdir -p /opt/gss
sudo cp target/*.jar /opt/gss/gss.jar

# 6. 创建后端服务
echo "创建后端服务..."
sudo tee /etc/systemd/system/gss.service > /dev/null <<EOF
[Unit]
Description=GSS Scholarship System
After=network.target

[Service]
Type=simple
User=www-data
WorkingDirectory=/opt/gss
ExecStart=/usr/bin/java -jar gss.jar --spring.profiles.active=prod
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

# 7. 构建前端
echo "构建前端应用..."
cd ../../FrontendCode/vue-gss
npm install
npm run build

# 8. 部署前端
echo "部署前端..."
sudo mkdir -p /var/www/gss
sudo cp -r dist/* /var/www/gss/
sudo chown -R www-data:www-data /var/www/gss

# 9. 配置Nginx
echo "配置Nginx..."
sudo cp ../../deploy/nginx.conf /etc/nginx/sites-available/gss
sudo ln -sf /etc/nginx/sites-available/gss /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t
sudo systemctl reload nginx

# 10. 启动服务
echo "启动服务..."
sudo systemctl daemon-reload
sudo systemctl enable gss
sudo systemctl start gss

# 11. 检查服务状态
echo "检查服务状态..."
sudo systemctl status gss
sudo systemctl status nginx

echo "部署完成！"
echo "前端访问地址: http://your-domain.com"
echo "后端API地址: http://your-domain.com/api" 